package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired

    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        //微信服务端你地址---微信小程序官网查询
        String wxUrl = weChatProperties.getWxUrl();
        //请求参数---微信小程序官网查询
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",dto.getCode());
        map.put("grant_type",weChatProperties.getGrantType());
        //获取响应体
        String result = HttpClientUtil.doGet(wxUrl, map); //result = {"session_key":"fxFFM3LUSNf7HK9o1pX6Hw==","openid":"o9cRz6_h7uUX79sDiYbG9PipUuOc"}
        //解析响应体Json数据
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = (String) jsonObject.get("openid");

        //判断openid是否为空
        //如果为空,则登陆失败,抛出异常
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //如果不为空,查找数据库user表,看openid是否存在
        User user = userMapper.select(openid);
        //如果不存在,先将用户添加到数据库User表中,添加openid,添加创建时间,然后回显ID
        if (user == null){
            user = User.builder().openid(openid).name( UUID.randomUUID().toString().replace("-","")).createTime(LocalDateTime.now()).build();
            userMapper.insert(user);
        }

        //将得到的user_id放入 ThreadLocal 内
        BaseContext.setCurrentId(user.getId());

        //如果存在,则为老用户,直接返回UserLoginVO
        //创建
        //获取Token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);
        UserLoginVO vo = new UserLoginVO(user.getId(),user.getOpenid(),token);
        return vo;
    }
}
